#!/bin/python
#-*- coding:utf-8 -*-
# Filename:    main.py
# Revision:    1.0
# Date:        2012-06-14
# Author:      simonzhang
# web:         www.simonzhang.net
# Email:       simon-zzm@163.com
### END INIT INFO
import sys
import ConfigParser
import StringIO

import tornado.ioloop
import tornado.locale
import tornado.web
from dbmodel import *
from interface import *


class GetProjectSetHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        _get_user = self.check_user()
        _domain, _title = if_get_domain_title()
        _project_name = self.get_argument("s")
        _project_info = odb_project_info(_project_name)
        _get_project_id = if_get_project_id(_project_name)
        _server_list = odb_project_server_list(_get_project_id)
        if u"%s" % _project_name == u"选择项目":
            return
        self.render("templates/getprojectset.html", domain=_domain, \
                                                    username = _get_user, \
                                                    projectn=_project_name, \
                                                    project_info = _project_info, \
                                                    server_list = _server_list)


class ProjectDefaultHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        _get_user = self.check_user()
        _project_name=self.get_argument("p")
        _get_default_reboot_value = self.get_argument("bootGroup1")
        _get_default_thread_value = self.get_argument("bootGroup2")
        _get_default_wait_time = self.get_argument("wait_time")
        _get_default_thread_num = self.get_argument("thread_num")
        if int(_get_default_thread_value) == 0:
            if int(_get_default_wait_time) < 1:
                _get_default_wait_time = 3
            _get_default_thread_num = 0
        else:
            _get_default_wait_time = 0
            if int(_get_default_thread_num) < 1:
                _get_default_thread_num = 2
        idb_insert_project_default(_project_name, _get_default_reboot_value, \
                                   _get_default_thread_value, _get_default_wait_time, \
                                   _get_default_thread_num)
        _domain, _title = if_get_domain_title()
        _get_user_left_menu = if_get_user_left_menu(_get_user)
        self.render("templates/returnpage.html", domain=_domain, \
                                                 title=_title, \
                                                 username = _get_user, \
                                                 items=_get_user_left_menu, \
                                                 nextpackage='/index/project_set/')

class EditSvnHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        _get_user = self.check_user()
        _project_name=self.get_argument("p")
        _get_svn_url = self.get_argument("svntextfield3")
        _get_svn_username = self.get_argument("svntextfield1")
        _get_svn_passwd = self.get_argument("svntextfield2")
        from interface import if_pass_encryption
        idb_svn(_project_name, _get_svn_username, \
                if_pass_encryption(_get_svn_passwd), \
                _get_svn_url)
        _domain, _title = if_get_domain_title()
        _get_user = self.get_secure_cookie("user").split(",")[0]
        _get_user_left_menu = if_get_user_left_menu(_get_user)
        self.render("templates/returnpage.html", domain=_domain, \
                                                 title=_title, \
                                                 username = _get_user, \
                                                 items=_get_user_left_menu, \
                                                 nextpackage='/index/project_set/')

class EditGitHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        _get_user = self.check_user()
        _project_name=self.get_argument("p")
        _get_git_url = self.get_argument("gittextfield6")
        _get_git_username = self.get_argument("gittextfield4")
        _get_git_passwd = self.get_argument("gittextfield5")
        from interface import if_pass_encryption
        idb_git(_project_name, _get_git_username, \
                if_pass_encryption(_get_git_passwd), \
                _get_git_url)
        _domain, _title = if_get_domain_title()
        _get_user = self.get_secure_cookie("user").split(",")[0]
        _get_user_left_menu = if_get_user_left_menu(_get_user)
        self.render("templates/returnpage.html", domain=_domain, \
                                                 title=_title, \
                                                 username = _get_user, \
                                                 items=_get_user_left_menu, \
                                                 nextpackage='/index/project_set/')

class TestVerConHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        _get_user = self.check_user()
        _domain, _title = if_get_domain_title()
        _get_user_left_menu = if_get_user_left_menu(_get_user)
        _project_name=self.get_argument("p")
        _get_version_config_manage = odb_project_info(_project_name)
        _svn_url = _get_version_config_manage['svn_url']
        _svn_user_name = _get_version_config_manage['svn_username']
        _svn_password = _get_version_config_manage['svn_password']
        _git_url = _get_version_config_manage['git_url']
        _git_user_name = _get_version_config_manage['git_username']
        _git_password = _get_version_config_manage['git_password']
        import subprocess
        _html_context = []
        if len(_svn_url) > 10:
            _run = subprocess.Popen('svn --version', shell=True, stdout=subprocess.PIPE)
            _reulst_version = _run.stdout.readlines()
            if len(_reulst_version) != 0:
                _html_context.append(r'%s' % _reulst_version[0])
            else:
                _html_context.append("没有安装SVN客户端工具")
            if len(_svn_user_name) == 0:
                _svn_comm = "svn info %s " % _svn_url
            else:
                _svn_comm = "svn info %s --username %s --password %s" % (_svn_url, \
                                                                         _svn_user_name, \
                                                                         if_pass_decryption(_svn_password))
            _run = subprocess.Popen(_svn_comm, shell=True, stdout=subprocess.PIPE)
            _test_svn_url = _run.stdout.readlines()
            if len(_test_svn_url) > 0:
                for i in _test_svn_url:
                    _html_context.append(r'%s' % i)
            else:
                _html_context.append("SVN URL 获取信息系错误请检查。")
        if len(_git_url) > 10:
            _run = subprocess.Popen('svn --version', shell=True, stdout=subprocess.PIPE)
            _reulst_version = _run.stdout.readlines()
            if len(_reulst_version) != 0:
                _html_context.append(r'%s' % _reulst_version[0])
            else:
                _html_context.append("没有安装SVN客户端工具")
            if len(_git_user_name) == 0:
                _git_comm = "svn info %s " % _git_url
            else:
                _git_comm = "svn info %s --username %s --password %s" % (_git_url, \
                                                                         _git_user_name, \
                                                                         if_pass_decryption(_git_password))
            _run = subprocess.Popen(_git_comm, shell=True, stdout=subprocess.PIPE)
            _test_git_url = _run.stdout.readlines()
            if len(_test_git_url) > 0:
                for i in _test_git_url:
                    _html_context.append(r'%s' % i)
            else:
                _html_context.append("GIT URL 获取信息系错误请检查。")
        self.render("templates/mycontext.html", domain=_domain, \
                                                title=_title, \
                                                username = _get_user, \
                                                items=_get_user_left_menu, \
                                                error_context=_html_context)


class VerManDefaultHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        _get_user = self.check_user()
        _project_name=self.get_argument("p")
        _ver_man_default = self.get_argument("VersionManageGroup2")
        idb_version_manage_default(_ver_man_default, _project_name)
        _domain, _title = if_get_domain_title()
        _get_user = self.get_secure_cookie("user").split(",")[0]
        _get_user_left_menu = if_get_user_left_menu(_get_user)
        self.render("templates/returnpage.html", domain=_domain, \
                                                 title=_title, \
                                                 username = _get_user, \
                                                 items=_get_user_left_menu, \
                                                 nextpackage='/index/project_set/')

class UploadConfileHandler(BaseHandler):
    @tornado.web.authenticated
    def post(self):
        _get_user = self.check_user()
        _domain, _title = if_get_domain_title()
        _get_user = self.get_secure_cookie("user").split(",")[0]
        _get_user_left_menu = if_get_user_left_menu(_get_user)
        error_context = ""
        _get_porject_name = self.get_argument('p')
        _get_project_id = if_get_project_id(_get_porject_name)
        if int(_get_project_id) == 0:
            return 0
        try:
            _get_file = self.request.files["confile"][0]['body']
        except:
            self.render("templates/mycontext.html", domain=_domain, \
                         title=_title, username = _get_user, \
                         items=_get_user_left_menu, \
                         error_context=["未选上传文件"])
        import re
        _get_file = re.sub(r'(\r\n|\r|\n)', '\n', _get_file)
        _tmp_file = StringIO.StringIO()
        _tmp_file.write(_get_file)
        _tmp_file.seek(0)
        if _tmp_file.read(3).startswith('\xef\xbb\xbf'):
            _tmp_file.seek(3)
        else:
            _tmp_file.seek(0)
        try:
            cf = ConfigParser.SafeConfigParser()
            cf.readfp(_tmp_file)
            config_list = cf.sections()
            if len(config_list) != len(config_list):
                self.render("templates/mycontext.html", domain=_domain, \
                             title=_title, items=_get_user_left_menu, \
                             error_context=["配置中服务名称有重复"])
        except:
            _tmp_file.close()
            self.render("templates/mycontext.html", domain=_domain, \
                         title=_title, items=_get_user_left_menu, \
                         error_context=["配置文件有误无法导入"])
        _tmp_file.close()
        for idb_conf in  config_list:
            if idb_conf == "versionconfigmanage":
                options = cf.options(idb_conf)
                _svn_url = cf.get(idb_conf, 'svnurl')
                _svn_user = cf.get(idb_conf, 'svnusername')
                _svn_passwd = cf.get(idb_conf, 'svnpasswd')
                _git_url = cf.get(idb_conf, 'giturl')
                _git_user = cf.get(idb_conf, 'gitusername')
                _git_passwd = cf.get(idb_conf, 'gitpasswd')
                _status = idb_version_config_update(_get_project_id, _svn_url, _svn_user, \
                                                    if_pass_encryption(_svn_passwd), \
                                                    _git_url, _git_user, \
                                                    if_pass_encryption(_git_passwd))
                if _status == "ERROR":
                    error_context = "版本管理部分升级数据库错误"
                continue
            if idb_conf == 'afterdeploydo':
                options = cf.options(idb_conf)
                _defaul_treboot = cf.get(idb_conf, 'defaultreboot')
                _wait_time = cf.get(idb_conf, 'waittime')
                _thread = cf.get(idb_conf, 'thread')
                _threadnum = cf.get(idb_conf, 'threadnum')
                _remark = cf.get(idb_conf, 'remark')
                _status = idb_after_deploy_do(_defaul_treboot, _wait_time, \
                                              _thread, _threadnum, _remark)
                if _status == "ERROR":
                    error_context = "部署完成后操作动作部分，升级数据库错误"
                continue
            options = cf.options(idb_conf)
            _host = cf.get(idb_conf, 'host')
            if len(_host) == 0:
                error_context += "IP 为空。"
            _port = cf.get(idb_conf, 'port')     
            _user = cf.get(idb_conf, 'user')
            if len(_user) == 0:
                error_context += "用户名为空。"
            _password = cf.get(idb_conf, 'password')
            _password = if_pass_encryption(_password)
            _remote_path = cf.get(idb_conf, 'remote_path')
            if len(_remote_path) == 0:
                error_context += "目录名为空。"
            _reboot_comm = cf.get(idb_conf, 'reboot_comm')
            _shutdown = cf.get(idb_conf, 'shutdown')
            _startup = cf.get(idb_conf, 'startup')
            _checkurl = cf.get(idb_conf, 'checkurl')
            if len(error_context) > 0:
                self.render("templates/mycontext.html", domain=_domain, \
                             title=_title, username = _get_user, \
                             items=_get_user_left_menu, \
                             error_context=["%s" % _get_porject_name, error_context])
            else:
                project_server_have = odb_projcet_server_count(idb_conf, _get_project_id)
                if project_server_have == 0:
                    _status = idb_project_server_insert(idb_conf, _get_project_id, 
                                  _host, _port, _user, _password, _remote_path, \
                                  _reboot_comm, _shutdown, \
                                  _startup, _checkurl)
                    if _status == "ERROR":
                        error_context = "插入数据库错误"
                elif project_server_have == 1:
                    _status = idb_project_server_update(idb_conf, _get_project_id,
                                  _host, _port, _user, _password, _remote_path, \
                                  _reboot_comm, _shutdown, \
                                  _startup, _checkurl)
                    if _status == "ERROR":
                        error_context = "升级数据库错误"
                else:
                    error_context = "数据库中保存的该项目的服务信息错误"
                if len(error_context) > 0:
                    self.render("templates/mycontext.html", domain=_domain, \
                             title=_title, username = _get_user, \
                             items=_get_user_left_menu, \
                             error_context=["%s" % _get_porject_name, error_context])
        self.render("templates/mycontext.html", domain=_domain, \
                         title=_title, username = _get_user, \
                         items=_get_user_left_menu, \
                         error_context=[ "修改成功"])

class DownConfileHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        _get_user = self.check_user()
        _domain, _title = if_get_domain_title()
        _get_user_left_menu = if_get_user_left_menu(_get_user)
        _get_porject_name = self.get_argument('p')
        _get_project_id = if_get_project_id(_get_porject_name)
        _server_list = odb_project_server_list(_get_project_id)
        _tmp_file = StringIO.StringIO()
        cf = ConfigParser.SafeConfigParser()
        _info = {'ip':'host', 'port':'port', 'user':'user', 'passwd':'password', \
                 'remotepath':'remote_path', 'reboot':'reboot_comm', \
                 'shutdown':'shutdown', 'startup':'startup', 'checkurl':'checkurl'}
        for o in _server_list:
            cf.add_section(o.servername)
            for k in _info.keys():
                if k == 'passwd':
                    cf.set(o['servername'], _info[k], if_pass_decryption(o[k]))
                else:
                    cf.set(o['servername'], _info[k], o[k])
        _get_version_config = odb_version_config_list(_get_project_id)
        _version_config = {'svnurl':'svn_url', 'svnusername':'svn_username', 'svnpasswd':'svn_password', \
                           'giturl':'git_url', 'gitusername':'git_username', 'gitpasswd':'git_password'}
        cf.add_section('versionconfigmanage')
        for k in _version_config.keys():
            if (k == 'svnpasswd') or (k == 'gitpasswd'):
                if type(_get_version_config[0][_version_config[k]]) == type(None):
                    cf.set('versionconfigmanage', k, '')
                else:
                    cf.set('versionconfigmanage', k, if_pass_decryption(_get_version_config[0][_version_config[k]]))
            else:
                if type(_get_version_config[0][_version_config[k]]) == type(None):
                    cf.set('versionconfigmanage', k, '')
                else:
                    cf.set('versionconfigmanage', k, _get_version_config[0][_version_config[k]])
        _get_after_deploy_do = odb_after_deploy_do(_get_project_id)
        _after_deploy_do = {'defaultreboot':'default_reboot', 'waittime':'wait_time', \
                            'thread':'thread', 'threadnum':'thread_num', 'remark':'remark'}
        cf.add_section('afterdeploydo')
        for k in _after_deploy_do.keys():
            if type(_get_after_deploy_do[0][_after_deploy_do[k]]) == type(None):
                cf.set('afterdeploydo', k, '')
            else:
                cf.set('afterdeploydo', k, str(_get_after_deploy_do[0][_after_deploy_do[k]]))
        cf.write(_tmp_file)
        _tmp_file.seek(0)
        import os
        import random
        _ran_package_name = random.randint(10000, 99999)
        f = open('static/temp/%s.txt' % _ran_package_name, "wb")
        print >>f,_tmp_file.read().encode('utf-8')
        f.close()
        root_path = os.getcwd()
        os.system("python bin/timerdel.py -z %s/static/temp/%s.txt -w 600 &" % (root_path, _ran_package_name))
        self.render("templates/download.html", domain=_domain, title=_title, \
                                               username = _get_user, \
                                               items=_get_user_left_menu, \
                                               packagename= '%s.txt' % _ran_package_name) 

class DelServiceHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        _get_user = self.check_user()
        _domain, _title = if_get_domain_title()
        _get_user_left_menu = if_get_user_left_menu(_get_user)
        error_context = ""
        _service_id = self.get_arguments('cg13')
        for si in _service_id:
            try:
                _status = idb_del_service(si)
                if _status == 'ERROR':
                    error_context = "删除出错，部分数据可能已经被删除。"
            except:
                error_context = "删除出错，部分数据可能已经被删除。"
            if len(error_context) > 0:
                self.render("templates/mycontext.html", domain=_domain, \
                             title=_title, username = _get_user, \
                             items=_get_user_left_menu, \
                             error_context=[error_context])
        self.render("templates/mycontext.html", domain=_domain, \
                     title=_title, username = _get_user, \
                     items=_get_user_left_menu, \
                     error_context=["删除成功。"])


class UNLockHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        _get_user = self.check_user()
        _domain, _title = if_get_domain_title()
        _get_user_left_menu = if_get_user_left_menu(_get_user)
        _project_name = self.get_arguments('p')[0]
        _lock_type = self.get_arguments('locktype')[0]
        _lock_start = self.get_arguments('unlock')
        from shutil import rmtree
        from glob import glob
        from os import path
        from time import strftime
        _now_time = strftime('%Y%m%d%H%M%S')
        if int(_lock_type) == 1:
            try: 
                rmtree('project/TMP_%s_*' % _project_name)
            except:
                pass
            idb_make_package_unlock(_project_name, _now_time)
        else:
            idb_deploy_unlock(_project_name, _now_time)
        self.render("templates/mycontext.html", domain=_domain, \
                     title=_title, username = _get_user, \
                     items=_get_user_left_menu, \
                     error_context=["解锁成功"])


class ProjectSetHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        _get_user = self.check_user()
        _domain, _title = if_get_domain_title()
        _get_user_left_menu = if_get_user_left_menu(_get_user)
        _get_user_manage_project = if_get_user_project(_get_user)
        self.render("templates/project_set.html", \
                     domain=_domain, \
                     title=_title, \
                     username = _get_user, \
                     items=_get_user_left_menu, \
                     pros=_get_user_manage_project)
    def post(self):
        self.clear_all_cookies()
        self.redirect("/")

